package com.etongwl.commonutils;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 数据库文件管理
 */
public class AppFileUtils {

    /**
     * 导出数据库
     * @param mContext 上下文环境
     * @param outFile  输出文件（包括全路径例如sdcard/cc.db）
     * @param dbName 数据库名称
     */
    public boolean exportDBFile(Context mContext,File outFile,String dbName){
        try {
            FileInputStream fin = new FileInputStream(mContext.getDatabasePath(dbName));
            FileOutputStream fos = new FileOutputStream(outFile);
            byte[] buffer = new byte[4089];
            int len = -1;
            while ((len = fin.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fos.flush();
            fin.close();
            fos.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 获取所有表名称
     * @return
     */
    public String[] getAllTables(SQLiteDatabase mDb){
        Cursor c = null;
        String sql = "SELECT name FROM sqlite_master WHERE type='table';";
        String [] tables = null;
        // 查询操作
        try {
            c = mDb.rawQuery(sql, null);
            if (c != null && c.getCount()>0) {
                tables = new String[c.getCount()];
                int index = 0;
                for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
                    tables[index++] = c.getString(0);
                }
            }
        } catch (SQLiteException e) {
            e.printStackTrace();
        } finally {
            // 关闭游标对象
            if (null != c) {
                c.close();
            }
        }
        return tables;
    }


    /**
     * 导出文件
     * @param sourceFile 目标文件
     * @param outfile  输出文件（包括全路径例如sdcard/a.db)
     */
    public boolean exportFile(String sourceFile,File outfile){
        try {
            FileInputStream fin = new FileInputStream(sourceFile);
            FileOutputStream fos = new FileOutputStream(outfile);
            byte[] buffer = new byte[4089];
            int len = -1;
            while ((len = fin.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fos.flush();
            fin.close();
            fos.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }



    /**
     * 获取表数据
     */
    public String getTableInfo(SQLiteDatabase mDb,String tablename) {
        StringBuffer sb = new StringBuffer();
        sb.append("TableName: ").append(tablename).append("\r\n");
        Cursor c = null;
        // 查询操作
        try {
            c = mDb.query(tablename, null, null, null, null, null, null);
            if (c != null) {
                // 显示列名
                String[] columsNames = c.getColumnNames();
                int totalIndex = columsNames.length;// 列名
                int index = 0;// 索引
                for(index=0; index<totalIndex; index++){
                    sb.append(columsNames[index]);
                    if(index != (totalIndex-1)){
                        sb.append("  |  ");
                    }
                }
                sb.append("\r\n");

                // 显示数据
                if(c.getCount() > 0){
                    for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
                        for(index=0; index<totalIndex; index++){
//							if(c.getType(index) != Cursor.FIELD_TYPE_BLOB){
                            sb.append(c.getString(index));
                            if(index != (totalIndex-1)){
                                sb.append("  |  ");
                            }
                        }
//						}
                        sb.append("\r\n");
                    }
                }
            }
        } catch (SQLiteException e) {
            e.printStackTrace();
        } finally {
            // 关闭游标对象
            if (null != c) {
                c.close();
            }
        }
        return sb.toString();
    }


    /**
     * 获取表中的数据
     * @return
     */
    public String getTableContents(SQLiteDatabase mDb){
        // 获取所有表名
        String[]  allTableNames = getAllTables(mDb);
        StringBuffer sb = new StringBuffer();
        int index = 0;
        int length = allTableNames.length;
        for(index=0; index<length; index++){
            if("sqlite_sequence".equals(allTableNames[index]) || "android_metadata".equals(allTableNames[index])){
                continue;
            }
            sb.append(getTableInfo(mDb,allTableNames[index]));
            if(index != (length-1)){
                sb.append("============================================\r\n");
            }
        }

        return sb.toString();
    }

    /**
     * 获取SharedPreferences中的所有数据
     * @return
     */
    public String getSPContents(SharedPreferences sp){
        HashMap<String, String> values = (HashMap<String, String>) sp.getAll();
        StringBuffer sb = new StringBuffer();
        for (Iterator iter = values.entrySet().iterator(); iter.hasNext();) {
            Map.Entry entry = (Map.Entry) iter.next();
            sb.append(entry.getKey()).append(" = ").append(entry.getValue()).append("\r\n");
        }
        return sb.toString();
    }
}
